import React, { useState,useEffect } from 'react';
import {Icon} from 'antd'

import './sorter.css'

export default ({
    title,
    field,
    onChange=()=>{},
    clear
})=>{
    const [order,setOrder]=useState()

    const handleSortClick=(ord,e)=>{
        e.stopPropagation()
        if(order!==ord){
            setOrder(ord)
            onChange({field,order:ord})
        }
    }

    useEffect(()=>{
        if(clear){
            setOrder()
        }
    },[clear])

    return (
        <div
            className="sorter"
            onClick={handleSortClick.bind(null,undefined)}
        >
            <div className="sorter_title">
                {typeof title==='function'?title():title}
            </div>
            <div className="sorter_icon">
                <Icon 
                    className={order==='ascend'&&'active'}
                    type="caret-up"
                    onClick={handleSortClick.bind(null,'ascend')}
                />
                <Icon 
                    className={order==='descend'&&'active'}
                    type="caret-down"
                    onClick={handleSortClick.bind(null,'descend')}
                />
            </div>
        </div>
    )
}
